package com.gitee.melin.bee.core.fs.impl;

import com.gitee.melin.bee.core.fs.FileSystem;
import com.gitee.melin.bee.core.fs.FsConnectionInfo;
import com.obs.services.ObsClient;
import com.obs.services.ObsConfiguration;
import com.obs.services.model.ListBucketsRequest;
import com.obs.services.model.ObsBucket;
import java.util.List;
import java.util.stream.Collectors;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HuaweiObsFileSystem implements FileSystem {
    private static final Logger LOGGER = LoggerFactory.getLogger(HuaweiObsFileSystem.class);

    @Override
    public String testConnection(FsConnectionInfo connectionInfo) {
        ObsConfiguration config = new ObsConfiguration();
        config.setSocketTimeout(30000);
        config.setConnectionTimeout(10000);
        config.setEndPoint(connectionInfo.getEndpoint());

        try (ObsClient obsClient =
                new ObsClient(connectionInfo.getAccessKeyId(), connectionInfo.getSecretAccessKey(), config)) {

            String bucket = connectionInfo.getBucket();
            if (StringUtils.isNotBlank(bucket)) {
                List<String> buckets = this.queryBuckets(obsClient);
                if (!buckets.contains(connectionInfo.getBucket())) {
                    throw new IllegalArgumentException("bucket not exist: " + bucket);
                }
            }

            return "Success";
        } catch (Exception e) {
            throw new RuntimeException("obs test connection error: " + e.getMessage(), e);
        }
    }

    @Override
    public List<String> queryBuckets(FsConnectionInfo connectionInfo) {
        ObsConfiguration config = new ObsConfiguration();
        config.setSocketTimeout(30000);
        config.setConnectionTimeout(10000);
        config.setEndPoint(connectionInfo.getEndpoint());

        try (ObsClient obsClient =
                new ObsClient(connectionInfo.getAccessKeyId(), connectionInfo.getSecretAccessKey(), config)) {

            return this.queryBuckets(obsClient);
        } catch (Exception e) {
            throw new RuntimeException("obs test connection error: " + e.getMessage(), e);
        }
    }

    private List<String> queryBuckets(ObsClient obsClient) {
        List<ObsBucket> buckets = obsClient.listBuckets(new ListBucketsRequest());
        return buckets.stream().map(ObsBucket::getBucketName).collect(Collectors.toList());
    }
}
